/*
 * FunctionDeclAst.cpp
 *
 *  Created on: 19 Nov 2010
 *      Author: kn308
 */

#include <MAlice/Parser/location.hh>
#include <MAlice/Codegen.h>
#include <MAlice/Ast/FunctionDeclAst.h>
#include <MAlice/Ast/FunctionParameterAst.h>
#include <MAlice/Ast/IntegerLiteralAst.h>

namespace MAlice
{

FunctionDeclAst::FunctionDeclAst(location loc, FunctionProtoAst* proto, ListAst* body) :
		Ast(loc), mProto(proto), mBody(body)
{
	MALICE_TRACE;
}

FunctionDeclAst::~FunctionDeclAst()
{
	MALICE_TRACE;
}

llvm::Value* FunctionDeclAst::generate()
{
	MALICE_TRACE;
	Codegen* g = Codegen::get();
	// start function scope
	MALICE_AUTO_REVERSE(g);

	// get the function entry from the prototype
	Function* F = reinterpret_cast<Function*> (mProto->generate());

	g->setFunction(F);
	if (NULL == mBody->generate())
	{
		cerr << "Warning: Function '" << F->getNameStr() << "' seems to contain invalid body." << endl;
	}

	// return the default constructor for all functions
	Builder* builder = g->getBuilder();
	TypeAst* ret = mProto->getReturnType();
	if (ret->type()->isVoidTy())
	{
		builder->CreateRetVoid();
	}
	else
	{
		builder->CreateRet(g->getDefaultValue(ret->getName())->generate());
	}

	return F;
}

}
